<?php
Authenticate::requireAccounting();
$db = Db::getInstance();
$db->autocommit(false);
try{
	if($_SERVER['REQUEST_METHOD'] == 'DELETE'){
		parse_str(file_get_contents("php://input"), $formData);
	    Package::instance()->hidePackage($formData['id']);
		$db->commit();
		echo json_encode(array('success'=> true));
	}
	else if($_SERVER['REQUEST_METHOD'] == 'GET'){
		$package = Package::instance()->getOne($_GET['id']);
        Table::instanceTable('Price')->joinOneTo('prices', 'packageId', 'id', $package, Table::JOIN_MANY);
		echo json_encode($package);
	}
	else if($_SERVER['REQUEST_METHOD'] == 'PUT'){
        $pdo = Db::getPDO();
        $pdo->beginTransaction();
        try {
            parse_str(file_get_contents("php://input"), $formData);
            $st = $pdo->prepare("UPDATE Package SET name=:name,info=:info WHERE id=:id");
            $st->execute(array(
                'name'=> $formData['name'],
                'info'=> $formData['info'],
                'id'=> $formData['id']
            ));
            $attr = array();

            $attr[] = $formData['id'];
            $in = array();

            $stInsert = $pdo->prepare("
                INSERT INTO Price(packageId,price,month)
                    SELECT * FROM (SELECT :packageId AS packageId,:price AS price,:month AS month) AS tmp
                    WHERE
                        NOT EXISTS (SELECT * FROM Price WHERE packageId=:packageId AND month=:month)
                        LIMIT 1;
                ");
            $stUpdate = $pdo->prepare("UPDATE Price SET price=:price WHERE month=:month AND packageId=:packageId LIMIT 1");
            foreach($formData['prices'] as $key => $price){
                if(empty($price['month']) || empty($price['']))
                $stInsert->execute(array(
                    'packageId'=> $formData['id'],
                    'price'=> $price['price'],
                    'month'=> $price['month']
                ));
                if($stInsert->rowCount()==0){
                    $stUpdate->execute(array(
                        'packageId'=> $formData['id'],
                        'price'=> $price['price'],
                        'month'=> $price['month']
                    ));
                }
                $in[] = '?';
                $attr[] = $price['month'];
            }
            $in = implode(',', $in);
            $st = $pdo->prepare("DELETE FROM Price WHERE packageId= ? AND month NOT IN({$in})");
            $st->execute($attr);

            $pdo->commit();
            echo json_encode(array('success'=> true));
        }
        catch(PDOException $ex){
            $pdo->rollBack();
            Log::error($ex);
            echo json_encode(array('success'=> false));
        }
        catch(Exception $ex){
            $pdo->rollBack();
            Log::error($ex);
            echo json_encode(array('success'=> false));
        }
	}
	else if($_SERVER['REQUEST_METHOD'] == 'POST'){
        Db::getPDO()->beginTransaction();
        Package::instance()->add(array(
            'type'=> $_POST['type'],
            'name'=> $_POST['name'],
            'info'=> $_POST['info'],
            'status'=> 1
        ));
        $id = Db::getPDO()->lastInsertId();
        foreach($_POST['prices'] as $key => $value){
            Price::instance()->add(array(
                'packageId'=> $id,
                'price'=> $value['price'],
                'month'=> $value['month'],
            ));
        }

        Db::getPDO()->commit();
		echo json_encode(array('success'=> true));
	}
}catch(Exception $ex){
	$db->rollback();
	Log::error($ex->getMessage());
	echo json_encode(array('success'=> false));
}